package com.fengxu.gamescript.ui.cloud

import android.content.Context
import android.graphics.Color
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONObject
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.Conf
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.data.po.NetScript
import com.fengxu.gamescript.data.vo.ExistScript
import com.fengxu.gamescript.provide.ProviderFactory
import com.fengxu.gamescript.ui.base.BaseActivity
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.toast.XToast
import github.ishaan.buttonprogressbar.ButtonProgressBar
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.find
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.toast
import org.joda.time.DateTime
import java.io.File

/**
 * 云脚本列表适配器
 */
class NetScriptListAdapter : RecyclerView.Adapter<NetScriptListAdapter.NetScriptHolder> {

    /**
     * 存放网络脚本组件
     */
    class NetScriptHolder(view: View): RecyclerView.ViewHolder(view) {

        // 脚本名组件
        val scriptNameView: TextView by lazy {
            view.findViewById(R.id.list_net_name)
        }

        // 脚本作者组件
        val scriptAuthorView: TextView by lazy {
            view.findViewById(R.id.list_net_author)
        }

        /**
         * 脚本创建时间组件
         */
        val scriptUpdateTimeView: TextView by lazy {
            view.findViewById(R.id.list_net_time)
        }

        // 脚本类型组件
        val scriptTypeView:TextView by lazy {
            view.findViewById(R.id.list_net_type)
        }

        // 脚本下载组件
        val scriptDownloadView: ButtonProgressBar by lazy {
            view.find(R.id.list_net_down)
        }
    }

    // 上下文
    private var mContext: Context

    // 网络脚本数据列表
    var datas: MutableList<NetScript>

    // 云服务次数改变事件
    var cloudTimesChanged: ((Int)->Unit)? = null

    constructor(ctx: Context, scripts: MutableList<NetScript>){
        mContext = ctx
        datas = scripts
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NetScriptHolder {
        val view = LayoutInflater.from(mContext).inflate(R.layout.list_net_script, parent, false)
        return NetScriptHolder(view)
    }

    override fun onBindViewHolder(holder: NetScriptHolder, position: Int) {
        val script = datas[position]
        holder.scriptNameView.text = script.name
        holder.scriptAuthorView.text = script.author
        holder.scriptUpdateTimeView.text = DateTime(script.updateTime).toString("yyyy-MM-dd")
        holder.scriptTypeView.text = when(script.type){
            0 -> "安卓原神"
            1 -> "PC原神"
            else -> "未知脚本"
        }
        // 设置下载按钮属性,添加下载事件
        holder.scriptDownloadView.run {
            onClick { downloadScript(holder.scriptDownloadView, script.id) }
            setBackgroundColor(mContext.resources.getColor(R.color.skyblue,null))
            setButtonText(this,"下载脚本")
        }
        // 根据用户下载脚本的情况设置不不同的按钮提示文字和颜色
        val existScript = Conf.getConf().existScriptList.find { it.id == script.id }
        holder.scriptDownloadView.isEnabled = true
        if(existScript != null){
            if(script.updateTime > existScript.time){
                setButtonText(holder.scriptDownloadView, "有更新")
                holder.scriptDownloadView.setBackgroundColor(Color.GREEN)
            }else{
                setButtonText(holder.scriptDownloadView, "已下载")
                holder.scriptDownloadView.setBackgroundColor(Color.parseColor("#4169E1"))
                holder.scriptDownloadView.isEnabled = false
            }
        }
    }

    /**
     * 下载脚本
     * @param id 脚本的ID
     */
    private fun downloadScript(btn: ButtonProgressBar,id: String){
        btn.startLoader()
        doAsync {
            val result = ProviderFactory.dataProvider.getMusicContent(id)
            if(result == null){
                mContext.runOnUiThread {
                    btn.stopLoader()
                    btn.reset()
                    XToast.error(mContext,"网络连接错误!").show()
                    return@runOnUiThread
                }
            }
            when(result.code){
                200->{
                    val netScript = JSONObject.parseObject(result.data.toString(), NetScript::class.java)
                    netScript.id = id
                    if(result.remainTimes != null){
                        mContext.runOnUiThread { cloudTimesChanged?.invoke(result.remainTimes) }
                    }
                    // 保存该下载的文件
                    mContext.runOnUiThread {
                        existFile(btn,netScript)
                    }
                }
                else -> {
                    mContext.runOnUiThread {
                        btn.stopLoader()
                        btn.reset()
                        XToast.error(mContext,result.msg).show()
                    }
                }
            }
        }
    }

    /**
     * 保存下载的云脚本
     */
    private fun existFile(btn: ButtonProgressBar, netScript: NetScript){
        val existScript = Conf.getConf().existScriptList.find { it.id == netScript.id }
        val existInvoke: (File)->Unit = {
            doAsync {
                it.writeText(netScript.content)
                Conf.getConf().existScriptList.removeIf { it.id == netScript.id }
                Conf.getConf().existScriptList.add(ExistScript(netScript.id,netScript.updateTime,it.path))
                Conf.saveConf(mContext)
                mContext.runOnUiThread {
                    btn.stopLoader()
                    XToast.success(mContext,"下载成功").show()
                }
            }
        }
        if(existScript != null){
            // 已经下载过再次下载,覆盖原文件
            existInvoke.invoke(File(existScript.existPath))
        }else{
            var filename = "${GlobalData.MusicScriptFolderPath}/${netScript.name}.js"
            // 同名文件存在
            if(File(filename).exists()){
                MaterialDialog.Builder(mContext)
                    .title("警告").content("检测到存在同名的文件,请输入新的文件名")
                    .inputType(InputType.TYPE_CLASS_TEXT).inputRange(0,32)
                    .input("重命名文件",netScript.name,false){dialog,text->
                        filename = "${GlobalData.MusicScriptFolderPath}/${text}.js"
                        if(File(filename).exists()){
                            dialog.dismiss()
                            existFile(btn, netScript)
                        }else{
                            existInvoke.invoke(File(filename))
                        }
                    }.positiveText("保存")
                    .cancelable(false)
                    .show()
            }else{
                existInvoke.invoke(File(filename))
            }
        }
    }

    /**
     * 反射设置ButtonProgressBar的文字
     */
    private fun setButtonText(btn: ButtonProgressBar, text: String){
        val field = btn.javaClass.getDeclaredField("mInitialText")
        field.isAccessible = true
        field.set(btn,text)
        btn.reset()
    }

    override fun getItemCount(): Int {
        return datas.size
    }

}